package initfabric

import (
	"fmt"
	"github.com/hyperledger/fabric-sdk-go/pkg/client/channel"
	"github.com/kongyixueyuan.com/kongyixueyuan/sdkInit"
	"os"
)

const (
	configFile  = "config.yaml"
	initialized = false
	SimpleCC    = "eduCC"
)

type ChannelClient struct {
	Client *channel.Client
}

var cli *ChannelClient

func NewChannelClient() *ChannelClient {
	cli = &ChannelClient{Client: InitFabric()}
	return cli
}

func InitFabric() *channel.Client {

	initInfo := &sdkInit.InitInfo{

		ChannelID:       "kevinkongyixueyuan",
		ChannelConfig:   os.Getenv("GOPATH") + "/src/github.com/kongyixueyuan.com/kongyixueyuan/fixtures/artifacts/channel.tx",
		OrgAdmin:        "Admin",
		OrgName:         "Org1",
		OrdererOrgName:  "orderer.kevin.kongyixueyuan.com",
		ChaincodeID:     SimpleCC,
		ChaincodeGoPath: os.Getenv("GOPATH"),
		ChaincodePath:   "github.com/kongyixueyuan.com/kongyixueyuan/chaincode/",
		UserName:        "User1",
	}

	sdk, err := sdkInit.SetupSDK(configFile, initialized)
	if err != nil {
		fmt.Printf(err.Error())
		return nil
	}

	//defer sdk.Close() // 注意修改

	err = sdkInit.CreateChannel(sdk, initInfo)
	if err != nil {
		fmt.Println(err.Error())
		return nil
	}
	channelClient, err := sdkInit.InstallAndInstantiateCC(sdk, initInfo)
	if err != nil {
		fmt.Println(err.Error())
		return nil
	}
	return channelClient

}
